package com.example.bilibili_miaosha.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.bilibili_miaosha.entity.*;
import com.example.bilibili_miaosha.mapper.OrderMapper;
import com.example.bilibili_miaosha.service.IGoodsService;
import com.example.bilibili_miaosha.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bilibili_miaosha.service.ISeckillGoodsService;
import com.example.bilibili_miaosha.service.ISeckillOrderService;
import com.example.bilibili_miaosha.vo.GoodsVO;
import com.example.bilibili_miaosha.vo.OrderDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 * 弓川hello mybatisplus
 *
 * @author gongchuan
 * @since 2022-04-01
 */
@Transactional //标记这是一个事务，原子性
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    /**
     * @Description: 秒杀功能
     * @Param: [user, goods]
     * @return: com.example.bilibili_miaosha.entity.Order
     * @Author: 弓川
     * @Date: 2022/4/3
     **/
    public Order seckill(User user, Goods goods) {
        System.out.println("******************");
        System.out.println(user);
        System.out.println(goods);
        if (user == null) {
            System.out.println("用户为空");
        }
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goods.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
//        seckillGoodsService.updateById(seckillGoods);//还需要将数据库中的这个也刷新一下   直接这样可能造成库存超卖
        //下面这条语句保证只有库存》0时，才会执行减库存操作
        boolean seckillResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().set("stock_count", seckillGoods.getStockCount()).eq("id", seckillGoods.getId()).gt("stock_count", 0));
        if (!seckillResult) {
            return null; // 如果更新数据库失败，直接返回null
        }

        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId("");
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getGoodsPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateTime(new Date());
        orderMapper.insert(order);
        /*Long userId = user.getId();
        Long goodsId = goods.getId();
        String goodsName = goods.getGoodsName();
        Integer goodsCount = order.getGoodsCount();
        BigDecimal goodsPrice = order.getGoodsPrice();
        Integer orderChannel = order.getOrderChannel();
        Integer status = order.getStatus();
        Date createTime = order.getCreateTime();
        orderMapper.insertOrder(userId, goodsId, goodsName, goodsCount, goodsPrice, orderChannel, status, createTime);*/

        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrderService.save(seckillOrder);
        redisTemplate.opsForValue().set("order:" + user.getId() + ":" + goods.getId(), seckillOrder); //存到redis里面


        return order;
    }

    @Override
    public OrderDetailVo detail(Long orderId) {

        Order order = orderMapper.selectById(orderId);
        GoodsVO goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo detail = new OrderDetailVo();
        detail.setGoodsVo(goodsVo);
        detail.setOrder(order);
        return detail;
    }

    @Override
    /** 
    * @Description: 检查验证码 
    * @Param: [user, goodsId, captcha]  user登录拦截器自动赋予
    * @return: boolean 
    * @Author: 弓川
    * @Date: 2022/5/13 
    **/ 
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (StringUtils.isEmpty(captcha) || null == user || goodsId < 0) {
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" +
                user.getId() + ":" + goodsId);
        return redisCaptcha.equals(captcha);
    }

    @Override
    /** 
    * @Description: 检验隐藏秒杀接口的地址，没做这个 
    * @Param: [user, goodsId] 
    * @return: java.lang.String 
    * @Author: 弓川
    * @Date: 2022/5/13 
    **/ 
    public String createPath(User user, Long goodsId) {
        return null;
    }
}
